package com.example.xmpic.ui.activity.setting;

import android.content.Intent;
import android.os.Message;

import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import android.view.View;

import com.alibaba.fastjson.JSON;
import com.basic.G;
import com.example.common.base.BaseBindActivity;
import com.example.common.utils.LiveDataBus;
import com.example.xmpic.R;
import com.example.xmpic.databinding.ActivityAlarmPeriodBinding;
import com.example.xmpic.support.FunSupport;
import com.example.xmpic.support.config.TimeItem;
import com.example.xmpic.support.models.FunDevice;
import com.example.xmpic.ui.adapter.AlarmPeriodAdapter;
import com.lib.EUIMSG;
import com.lib.FunSDK;
import com.lib.IFunSDKResult;
import com.lib.MsgContent;
import com.lib.SDKCONST;
import com.lib.sdk.bean.AlarmInfoBean;
import com.lib.sdk.bean.HandleConfigData;
import com.lib.sdk.bean.JsonConfig;
import com.lib.sdk.bean.StringUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * @author skygge
 * @date 2020/7/6.
 * GitHub：javofxu@github.com
 * email：skygge@yeah.net
 * description：报警时段设置页面
 */
public class CameraAlarmPeriodActivity extends BaseBindActivity<ActivityAlarmPeriodBinding> implements IFunSDKResult {
    private static final String ALL_DAY_OPEN = "1 00:00:00-24:00:00";
    public static final int REQUEST_CODE_SETTING_ALARM_TIME = 5;
    private HandleConfigData<Object> mConfigData;
    private AlarmInfoBean mAlarmInfo;
    private AlarmPeriodAdapter mAdapter;
    private List<TimeItem> mTimeList;
    private int mUserId;
    private FunDevice mFunDevice;
    private boolean isChanged = false;
    private int mAlarmType = 0;
    private int mCurrentType = 0;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_alarm_period;
    }

    @Override
    protected void initialize() {
        super.initialize();
        int deviceId = getIntent().getIntExtra("FUN_DEVICE_ID", 0);
        mFunDevice = FunSupport.getInstance().findDeviceById(deviceId);
        if ( null == mFunDevice ) {
            finish();
        }
    }

    @Override
    protected void initView() {
        super.initView();
        mDBind.alarmTimeList.setLayoutManager(new LinearLayoutManager(mContext));
    }

    @Override
    protected void initData() {
        super.initData();
        mUserId = FunSDK.RegUser(this);
        mConfigData = new HandleConfigData<>();
        FunSDK.DevGetConfigByJson(mUserId, mFunDevice.getDevSn(), JsonConfig.DETECT_MOTIONDETECT, 1024, 0, 5000, 0);
    }

    @Override
    protected void initDataBus() {
        super.initDataBus();
        LiveDataBus.get().with("FUN_ALARM_TIME", Integer.class).observe(this, integer -> {
            Intent intent = new Intent(mContext, SettingAlarmPeriodActivity.class);
            intent.putExtra("position", integer);
            intent.putExtra("timeInfo", mTimeList.get(integer));
            startActivityForResult(intent, REQUEST_CODE_SETTING_ALARM_TIME);
        });
    }

    @Override
    protected void initListener() {
        super.initListener();
        mDBind.rlAlarmAllDay.setOnClickListener(v -> {
            mDBind.alarmAllDay.setChecked(true);
            mDBind.alarmCustomTime.setChecked(false);
            mDBind.alarmTimeList.setVisibility(View.GONE);
        });
        mDBind.alarmAllDay.setOnCheckedChangeListener((buttonView, isChecked) -> {
            if (isChecked){
                mDBind.alarmCustomTime.setChecked(false);
                mDBind.alarmTimeList.setVisibility(View.GONE);
                mCurrentType = 1;
                showSaveUI();
            }
        });
        mDBind.rlAlarmCustomTime.setOnClickListener(v -> {
            mDBind.alarmAllDay.setChecked(false);
            mDBind.alarmCustomTime.setChecked(true);
            mDBind.alarmTimeList.setVisibility(View.VISIBLE);
        });
        mDBind.alarmCustomTime.setOnCheckedChangeListener((buttonView, isChecked) -> {
            if (isChecked){
                mDBind.alarmAllDay.setChecked(false);
                mDBind.alarmTimeList.setVisibility(View.VISIBLE);
                mCurrentType = 2;
                showSaveUI();
            }
        });
        mDBind.tvSavePeriod.setOnClickListener(v -> saveConfig());

        mDBind.alarmPeriodBack.setOnClickListener(v -> finish());
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CODE_SETTING_ALARM_TIME) {
            if (resultCode == RESULT_OK) {
                TimeItem timeInfo = (TimeItem) data.getSerializableExtra("timeInfo");
                int position = data.getIntExtra("mPosition", -1);
                timeInfo.setTimeSection(position + 1, mAlarmInfo.EventHandler.TimeSection);
                mAdapter.update(position, timeInfo);
                isChanged = true;
                showSaveUI();
            }
        }
    }

    @Override
    public int OnFunSDKResult(Message message, MsgContent msgContent) {
        switch (message.what) {
            case EUIMSG.DEV_GET_JSON:
                if (JsonConfig.DETECT_MOTIONDETECT.equals(msgContent.str) || JsonConfig.DETECT_LOCAL_ALARM.equals(msgContent.str)) {
                    mConfigData.getDataObj(G.ToString(msgContent.pData), AlarmInfoBean.class);
                    FunSupport.getInstance().mAlarmInfoBean = (AlarmInfoBean) mConfigData.getObj();
                    mAlarmInfo = FunSupport.getInstance().mAlarmInfoBean;
                    parseData();
                }
                break;
            case EUIMSG.DEV_SET_JSON:
                dismissProgressDialog();
                if (JsonConfig.DETECT_MOTIONDETECT.equals(msgContent.str) || JsonConfig.DETECT_LOCAL_ALARM.equals(msgContent.str)) {
                    showToast(getString(R.string.success_set));
                }
                break;
            default:
                break;
        }
        return 0;
    }

    private void saveConfig() {
        if (null != mAlarmInfo) {
            showProgressDialog();
            for (int i = 0; i < SDKCONST.NET_N_WEEKS; i++) {
                mAlarmInfo.EventHandler.TimeSection[i][0] = String.format("%s %s:%s:%s-%s:%s:%s",
                        mDBind.alarmAllDay.isChecked() ? 1 : 0, "00", "00", "00", "24", "00", "00");
            }
            FunSupport.getInstance().mAlarmInfoBean = mAlarmInfo;
            FunSDK.DevSetConfigByJson(mUserId, mFunDevice.getDevSn(),
                    JsonConfig.DETECT_MOTIONDETECT, JSON.toJSONString(mAlarmInfo), 0, 5000, 0);
        }
    }

    private void parseData() {
        if (parseAllDay()){
            mAlarmType = 1;
            mDBind.alarmAllDay.setChecked(true);
            mDBind.alarmCustomTime.setChecked(false);
        }else {
            mAlarmType = 2;
            mDBind.alarmAllDay.setChecked(false);
            mDBind.alarmCustomTime.setChecked(true);
        }
        mTimeList = parseSomeDay();
        mAdapter = new AlarmPeriodAdapter(mContext, mTimeList);
        mDBind.alarmTimeList.setAdapter(mAdapter);
    }

    private boolean parseAllDay() {
        for (int i = 0; i < SDKCONST.NET_N_WEEKS; ++i) {
            String time = mAlarmInfo.EventHandler.TimeSection[i][0];
            if (!StringUtils.contrast(time, ALL_DAY_OPEN)) {
                return false;
            }
        }
        return true;
    }

    private List<TimeItem> parseSomeDay() {
        // 第一个时间段被用于判断是否为每天报警了
        List<TimeItem> alarmTimeInfo = new ArrayList<>();
        for (int i = 1; i < SDKCONST.NET_N_TSECT; ++i) {
            TimeItem info = new TimeItem();
            int weekMask = 0;
            String[] eachTime = null;
            for (int j = 0; j < SDKCONST.NET_N_WEEKS; ++j) {
                String time = mAlarmInfo.EventHandler.TimeSection[j][i];
                eachTime = time.split("\\W+");
                if (StringUtils.contrast(eachTime[0], "1")) {
                    info.setOpen(true);
                    info.setTime(eachTime[1] + ":" + eachTime[2] + "-" + eachTime[4] + ":" + eachTime[5]);
                    weekMask |= 1 << j;
                }
            }
            info.setWeekMask(weekMask);
            if (!info.isOpen()) {
                info.setTime(eachTime[1] + ":" + eachTime[2] + "-" + eachTime[4] + ":" + eachTime[5]);
            }
            alarmTimeInfo.add(info);
        }
        return alarmTimeInfo;
    }

    private void showSaveUI(){
        if (mCurrentType != mAlarmType || isChanged){
            mDBind.tvSavePeriod.setEnabled(true);
            mDBind.tvSavePeriod.setTextColor(ContextCompat.getColor(mContext, R.color.main_color));
        }else {
            mDBind.tvSavePeriod.setEnabled(false);
            mDBind.tvSavePeriod.setTextColor(ContextCompat.getColor(mContext, R.color.text_normal));
        }
    }
}
